priority -50

global !p
# A overkill(dirty) table with automatic alignment feature
def create_table(snip):
	# retrieving single line from current string and treat it like tabstops count
	placeholders_string = snip.buffer[snip.line].strip()
	rows_amount = int(placeholders_string[0])
	columns_amount = int(placeholders_string[1])

	prefix_str = "from vimsnippets import display_width;"

	# erase current line
	snip.buffer[snip.line] = ""

	# create anonymous snippet with expected content and number of tabstops
	anon_snippet_title = "| "
	anon_snippet_delimiter = "|"
	for col in range(1, columns_amount+1):
		sync_rows = [x*columns_amount+col for x in range(rows_amount+1)]
		sync_str = ",".join(["t[{0}]".format(x) for x in sync_rows])
		max_width_str = "max(list(map(display_width, [" + sync_str + "])))"
		cur_width_str = "display_width(t[" + str(col) + "])"
		rv_val = "(" + max_width_str + "-" + cur_width_str + ")*' '"
		anon_snippet_title += "${" + str(col)  + ":head" + str(col)\
			+ "}`!p " + prefix_str + "snip.rv=" + rv_val + "` | "
		anon_snippet_delimiter += ":`!p " + prefix_str + "snip.rv = "\
			+ max_width_str + "*'-'" + "`-|"

	anon_snippet_title += "\n"

	anon_snippet_delimiter += "\n"
	anon_snippet_body = ""
	for row in range(1, rows_amount+1):
		body_row = "| "
		for col in range(1, columns_amount+1):
			sync_rows = [x*columns_amount+col for x in range(rows_amount+1)]
			sync_str = ",".join(["t[{0}]".format(x) for x in sync_rows])
			max_width_str = "max(list(map(display_width, [" + sync_str + "])))"
			cur_width_str = "display_width(t[" + str(row*columns_amount+col) + "])"
			rv_val = "(" + max_width_str + "-" + cur_width_str + ")*' '"
			placeholder = "R{0}C{1}".format(row, col)
			body_row += "${" + str(row*columns_amount+col)  + ":" + placeholder\
				+ "}`!p " + prefix_str + "snip.rv=" + rv_val + "` | "

		body_row += "\n"
		anon_snippet_body += body_row

	anon_snippet_table = anon_snippet_title + anon_snippet_delimiter + anon_snippet_body

	# expand anonymous snippet
	snip.expand_anon(anon_snippet_table)

texMathZones = ['texMathZone' + x for x in ['A', 'AS', 'B', 'BS', 'C', 'CS',
'D', 'DS', 'E', 'ES', 'F', 'FS', 'G', 'GS', 'H', 'HS', 'I', 'IS', 'J', 'JS',
'K', 'KS', 'L', 'LS', 'DS', 'V', 'W', 'X', 'Y', 'Z', 'AmsA', 'AmsB', 'AmsC',
'AmsD', 'AmsE', 'AmsF', 'AmsG', 'AmsAS', 'AmsBS', 'AmsCS', 'AmsDS', 'AmsES',
'AmsFS', 'AmsGS' ]]

texIgnoreMathZones = ['texMathText']

texMathZoneIds = vim.eval('map('+str(texMathZones)+", 'hlID(v:val)')")
texIgnoreMathZoneIds = vim.eval('map('+str(texIgnoreMathZones)+", 'hlID(v:val)')")

ignore = texIgnoreMathZoneIds[0]

def math():
	synstackids = vim.eval("synstack(line('.'), col('.') - (col('.')>=2 ? 1 : 0))")
	try:
		first = next(
            i for i in reversed(synstackids)
            if i in texIgnoreMathZoneIds or i in texMathZoneIds
        )
		return first != ignore
	except StopIteration:
		return False
endglobal

###########################
# Sections and Paragraphs #
###########################
snippet sec "Section" b
# ${1:Section Name} #
$0
endsnippet

snippet ssec "Sub Section" b
## ${1:Section Name} ##
$0
endsnippet

snippet sssec "SubSub Section" b
### ${1:Section Name} ###
$0
endsnippet

snippet par "Paragraph" b
#### ${1:Paragraph Name} ####
$0
endsnippet

snippet spar "Paragraph" b
##### ${1:Paragraph Name} #####
$0
endsnippet

###################
# Text formatting #
###################

snippet * "italics"
*${1:${VISUAL}}*$0
endsnippet

snippet ** "bold"
**${1:${VISUAL}}**$0
endsnippet

snippet *** "bold italics"
***${1:${VISUAL}}***$0
endsnippet

snippet /* "Comment"
<!-- ${1:${VISUAL}} -->$0
endsnippet

################
# Common stuff #
################
snippet link "Link to something"
[${1:${VISUAL:Text}}](${3:http://${2:www.url.com}})$0
endsnippet

snippet img "Image"
![${1:pic alt}](${2:path}${3/.+/ "/}${3:opt title}${3/.+/"/})$0
endsnippet

snippet ilc "Inline Code" i
\`$1\`$0
endsnippet

snippet cbl "Codeblock" b
\`\`\`
$1
\`\`\`
$0
endsnippet

snippet refl "Reference Link"
[${1:${VISUAL:Text}}][${2:id}]$0

[$2]:${4:http://${3:www.url.com}} "${5:$4}"
endsnippet

snippet fnt "Footnote"
[^${1:${VISUAL:Footnote}}]$0

[^$1]:${2:Text}
endsnippet

snippet detail "Disclosure"
<details${3: open=""}>
  ${1:summary>${2}</summary>}$0
</details>
endsnippet

post_jump "create_table(snip)"
snippet "tb([1-9][1-9])" "Fancy table" br
`!p snip.rv = match.group(1)`
endsnippet

snippet box "Box"
`!p snip.rv = '┌' + '─' * (len(t[1]) + 2) + '┐'`
│ $1 │
`!p snip.rv = '└' + '─' * (len(t[1]) + 2) + '┘'`
$0
endsnippet

snippet beg "begin{} / end{}" b
\begin{$1}
	$0
\end{$1}
endsnippet

snippet mk "Math" w
$${1}$`!p
if t[2] and t[2][0] not in [',', '.', '?', '-', ' ']:
    snip.rv = ' '
else:
    snip.rv = ''
`$2
endsnippet

snippet dm "Math" w
\[
$1
.\] $0
endsnippet

# snippet '([A-Za-z])(\d)' "auto subscript" wrA
# `!p snip.rv = match.group(1)`_`!p snip.rv = match.group(2)`
# endsnippet
# 
# snippet '([A-Za-z])_(\d\d)' "auto subscript2" wrA
# `!p snip.rv = match.group(1)`_{`!p snip.rv = match.group(2)`}
# endsnippet

snippet sr "^2" i
^2
endsnippet

snippet cb "^3" i
^3
endsnippet

snippet compl "complement" i
^{c}
endsnippet

snippet td "superscript" i
^{$1}$0
endsnippet

snippet // "Fraction" i
\\frac{$1}{$2}$0
endsnippet

snippet '((\d+)|(\d*)(\\)?([A-Za-z]+)((\^|_)(\{\d+\}|\d))*)/' "Fraction" wr
\\frac{`!p snip.rv = match.group(1)`}{$1}$0
endsnippet

priority 1000
snippet '^.*\)/' "() Fraction" wrA
`!p
stripped = match.string[:-1]
depth = 0
i = len(stripped) - 1
while True:
	if stripped[i] == ')': depth += 1
	if stripped[i] == '(': depth -= 1
	if depth == 0: break;
	i -= 1
snip.rv = stripped[0:i] + "\\frac{" + stripped[i+1:-1] + "}"
`{$1}$0
endsnippet

# snippet / "Fraction" iA
# \\frac{${VISUAL}}{$1}$0
# endsnippet

priority 10
snippet "bar" "bar" ri
\overline{$1}$0
endsnippet

priority 100
snippet "([a-zA-Z])bar" "bar" ri
\overline{`!p snip.rv=match.group(1)`}
endsnippet

priority 10
snippet "hat" "hat" ri
\hat{$1}$0
endsnippet

priority 100
snippet "([a-zA-Z])hat" "hat" ri
\hat{`!p snip.rv=match.group(1)`}
endsnippet

snippet "(\\?\w+)(,\.|\.,)" "Vector postfix" ri
\vec{`!p snip.rv=match.group(1)`}
endsnippet

# vim:ft=snippets:
